package com.yinhe.music.yhmusic.downmanager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseFragment;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.bean.DownloadMusicEntity;
import com.yinhe.music.yhmusic.downmusic.DownloadTask;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.service.PlayService;
import com.yinhe.music.yhmusic.utils.MusicUtils;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


/**
 * @author hasee
 * @date 2017/2/23
 */

public class DownLoadFragment extends BaseFragment {
    private RecyclerView mRecycler;
    private int downPosition = -1;
    private DownLoadAdapter adapter;
    private LinearLayout mManager;
    private LinearLayout mStart;
    private ImageView start;
    public Activity mContext;
    private TextView mTextView, mCount;
    boolean isStart = false;
    List<DownloadMusicEntity> mInfo = new ArrayList<>();
    private final static String TAG = "DownLoadFragment";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.new_music_item, container, false);

        mRecycler = view.findViewById(R.id.recyclerView);
        mManager  = view.findViewById(R.id.manager);
        start     = view.findViewById(R.id.play_btn);
        mTextView = view.findViewById(R.id.text);
        mStart    = view.findViewById(R.id.play_layout);
        mCount    = view.findViewById(R.id.text_num);
        mCount.setVisibility(View.VISIBLE);
        setRecyclerView();
        setListener();
        RxBus.get().register(this);
        return view;
    }

    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    /**
     * 初始化RecyclerView
     */
    private void setRecyclerView() {
        adapter = new DownLoadAdapter();
        WrapContentLinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(getActivity());
        mRecycler.setLayoutManager(layoutManager);
        mRecycler.setAdapter(adapter);
        mRecycler.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, 0, true));
    }

    private void setHead() {
        MLog.debug("DownLoadFragment", "downTask:" + isStart);
        mTextView.setText("全部开始");
        mStart.setOnClickListener((v) -> {
            if (!isStart) {
                isStart = true;
                start.setImageResource(R.drawable.ic_stop_bottom);
                mTextView.setText(getString(R.string.all_paus));
                if (mService != null) {
                    mService.startAllDownloadTask();
                }
            } else {
                start.setImageResource(R.drawable.ic_play_bottom);
                mTextView.setText(getString(R.string.all_start));
                isStart = false;
                if (mService != null) {
                    mService.pauseAllDownloadTask();
                }
            }
        });
    }

    private void setListener() {
        mManager.setOnClickListener((v) -> {
            Intent intent = new Intent(getActivity(), DownLoadManagerActivity.class);
            startActivity(intent);
        });
    }

    private void initData() {
        if (mService != null) {
            mInfo = mService.getDownloadingMusicTaskList();
            adapter.update(mInfo, mService.getPrepareTaskList());
            MLog.info(TAG, "wywy  info size=" + mInfo.size() + "  prepare size" + mService.getPrepareTaskList().size() + " " + mInfo + " prepare=" + mService.getPrepareTaskList());
            if (isVisible()) {
                setHead();
                mCount.setText("(" + mInfo.size() + ")");
            }
            updateHeadViewStatus();
        }
    }

    /**
     * 更新下载列表数
     */
    private void setTaskSize() {
        mCount.setText(String.format(Locale.CHINESE, "(%d)", mInfo.size()));
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
        mCount.setText("(" + mInfo.size() + ")");
    }

    private DownloadMusicEntity removeMusicByID(long id) {
        if (mInfo == null || mInfo.size() == 0) {
            return null;
        }
        int index = 0;
        for (DownloadMusicEntity i : mInfo) {
            if (i.getSongid() == id) return mInfo.remove(index);
            index++;
        }
        return null;
    }

    private boolean isDownloading() {
        if (mService != null) {
            return mService.getPrepareTaskList().size() > 0;
        }
        return false;
    }

    private void updateHeadViewStatus() {
        if (isDownloading()) {
            start.setImageResource(R.drawable.ic_stop_bottom);
            mTextView.setText(getString(R.string.all_paus));
            isStart = true;
        } else {
            start.setImageResource(R.drawable.ic_play_bottom);
            mTextView.setText(getString(R.string.all_start));
            isStart = false;
        }

    }

    class DownLoadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private List<DownloadMusicEntity> mList;
        private List<Long> currentTaskList;
        private long completed = 0;
        private long totalsize = -1;

        public DownLoadAdapter(List list, List<Long> currentTaskList) {
            mList = list;
            this.currentTaskList = currentTaskList;
        }

        public void update(List list, List<Long> currentTaskList) {
            mList = list;
            this.currentTaskList = currentTaskList;
            completed = 0;
            totalsize = -1;
            notifyDataSetChanged();
        }


        public DownLoadAdapter() {

        }


        public void updateState(long completed, long tsize, long sID) {
            int index = 0;
            for (DownloadMusicEntity i : mInfo) {
                if (i.getID() == sID) {
                    i.speed = completed - i.getCompletedSize();
                    i.setCompletedSize(completed);
                    i.setToolSize(tsize);
                    break;
                }
                index++;
            }
            if (index < mInfo.size()) {
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_down_item, parent, false));
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            final DownloadMusicEntity task = mInfo.get(position);
            boolean isCurrent = false;
            boolean isPreparing = false;
            ((ItemViewHolder) holder).title.setText(task.getSongname());
//            switch (task.getQtype()) {
//                case IConstants.Common:
//                    ((ItemViewHolder) holder).quality.setImageResource(R.drawable.ic_regular);
//                    break;
//                case IConstants.HQ:
//                    ((ItemViewHolder) holder).quality.setImageResource(R.drawable.ic_hq);
//                    break;
//                case IConstants.SQ:
//                    ((ItemViewHolder) holder).quality.setImageResource(R.drawable.ic_sq);
//                    break;
//                default:
//                    break;
//            }
            if (currentTaskList.size() > 0) {
                isCurrent = currentTaskList.get(0).equals(task.getDownloadId());
                if (isCurrent) {
                    downPosition = position;
                }
                if (currentTaskList.contains(task.getDownloadId())) {
                    isPreparing = true;
                }
            }
            if (isCurrent) {
                completed = completed > task.getCompletedSize() ? completed : task.getCompletedSize();
                totalsize = totalsize > task.getTotalSize() ? totalsize : task.getTotalSize();
                ((ItemViewHolder) holder).size.setVisibility(View.VISIBLE);
                if (completed == 0 || totalsize == -1) {
                    ((ItemViewHolder) holder).size.setText("正在计算大小文件大小");
                    ((ItemViewHolder) holder).progressBar.setVisibility(View.GONE);
                } else {
                    ((ItemViewHolder) holder).size.setText((float) (Math.round((float) completed / (1024 * 1024) * 10)) / 10 + "M/" +
                            (float) (Math.round((float) totalsize / (1024 * 1024) * 10)) / 10 + "M");
                    if (((ItemViewHolder) holder).progressBar.getVisibility() != View.VISIBLE) {
                        ((ItemViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
                    }
                    if (totalsize > 0) {
                        ((ItemViewHolder) holder).progressBar.setProgress((int) (100 * completed / totalsize));
                    }
                }
                ((ItemViewHolder) holder).wait.setVisibility(View.GONE);
                ((ItemViewHolder) holder).speed.setText(Math.round((float) task.speed / 1024) + "KB/s");
                ((ItemViewHolder) holder).speed.setVisibility(View.VISIBLE);
            } else if (isPreparing) {
                ((ItemViewHolder) holder).wait.setVisibility(View.VISIBLE);
                ((ItemViewHolder) holder).progressBar.setVisibility(View.GONE);
                ((ItemViewHolder) holder).size.setVisibility(View.GONE);
                ((ItemViewHolder) holder).wait.setText("等待下载");
                ((ItemViewHolder) holder).speed.setVisibility(View.GONE);
            } else {
                ((ItemViewHolder) holder).wait.setVisibility(View.VISIBLE);
                ((ItemViewHolder) holder).progressBar.setVisibility(View.GONE);
                ((ItemViewHolder) holder).wait.setText("已经暂停，点击继续下载");
                ((ItemViewHolder) holder).size.setVisibility(View.GONE);
                ((ItemViewHolder) holder).speed.setVisibility(View.GONE);
            }

            ((ItemViewHolder) holder).more.setVisibility(View.GONE);
            final boolean isPre = isPreparing;
            ((ItemViewHolder) holder).itemView.setOnClickListener((v) -> {
                if (isPre) {
                    if (mService != null) mService.pauseDownloadTask(task.getDownloadId());
                } else {
                    if (mService != null) mService.resumeStartDownloadTask(task.getDownloadId());
                }
            });
            updateHeadViewStatus();
        }

        @Override
        public int getItemCount() {
            return mInfo.size();
        }

        class ItemViewHolder extends RecyclerView.ViewHolder {

            ImageView downloaded;
            ImageView more;
//            ImageView quality;
            TextView title;
            TextView speed;
            TextView size;
            TextView stop;
            TextView wait;
            ProgressBar progressBar;

            ItemViewHolder(View itemView) {
                super(itemView);
//                quality = itemView.findViewById(R.id.image);
                more = itemView.findViewById(R.id.down_more);
                title = itemView.findViewById(R.id.down_top_text);
                speed = itemView.findViewById(R.id.down_speed);
                size = itemView.findViewById(R.id.down_size);
                stop = itemView.findViewById(R.id.down_stop);
                wait = itemView.findViewById(R.id.down_wait);
                downloaded = itemView.findViewById(R.id.downloaded);
                progressBar = itemView.findViewById(R.id.down_progress);
                progressBar.setMax(100);
            }
        }
    }


    @Override
    public void onServiceConnected(PlayService service) {
        super.onServiceConnected(service);
        initData();
    }


    /**
     * 更新下载进度
     *
     * @param downloadTask 下载任务
     */
    @Subscribe(
        thread = EventThread.MAIN_THREAD,
        tags = {@Tag(RxBusEventType.Download.DOWNLOAD_PROCESS)})
    public void onRxbusDownloadStart(DownloadTask downloadTask) {
        if (downloadTask != null) {
            long cSize = downloadTask.getCompletedSize();
            long sId = downloadTask.getId();
            long tSixe = downloadTask.getTotalSize();
            adapter.updateState(cSize, tSixe, sId);
        }
    }


    /**
     * 更新下载状态
     *
     * @param downloadTask 下载任务
     */
    @Subscribe(
        thread = EventThread.MAIN_THREAD,
        tags = {@Tag(RxBusEventType.Download.DOWNLOAD_PAUSE),
                @Tag(RxBusEventType.Download.DOWNLOAD_START),
                @Tag(RxBusEventType.Download.DOWNLOAD_CANCEL),
                @Tag(RxBusEventType.Download.DOWNLOAD_COMPLETE)}
    )
    public void onRxbusDownloadEvent(DownloadTask downloadTask) {
        initData();
    }

    /**
     * 删除下载任务回传
     *
     * @param rxbusListObject 下载任务 {@link DownloadMusicEntity}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC)})
    public void onRxbusDeleteDownMusic(RxbusListObject rxbusListObject) {
        if (rxbusListObject.rxList != null) {
            for (Object i : rxbusListObject.rxList) {
                Integer downloadId = (Integer) i;
                DownloadMusicEntity tmp = removeMusicByID(downloadId);
                if (tmp != null) {
                    MusicUtils.deleteFile(getActivity(), tmp);
                }
            }
        }
        adapter.notifyDataSetChanged();
        setTaskSize();
    }
}
